import 'package:hinge/common/index.dart';
import 'package:hinge/common/models/video_comment_model.dart';
import 'package:uuid/uuid.dart';
import 'dart:math' as math;

class VideoCommentService {
  static const String _spKey = 'video_comments';
  static const Uuid _uuid = Uuid();

  // 初始化示例评论数据
  static Future<void> initSampleComments() async {
    final comments = await getAllComments();
    if (comments.isEmpty) {
      // 创建示例评论
      final sampleComments = [
        // 视频1评论
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 1,
          userId: 2,
          content:
              "This Is Pure Magic! 😆 Every Smile, Every Tear, It's All So Incredibly Beautiful!",
          createdAt: DateTime.now().subtract(Duration(days: 2)),
        ),
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 1,
          userId: 3,
          content: "Love this video! The fragrance looks amazing 💖",
          createdAt: DateTime.now().subtract(Duration(hours: 5)),
        ),

        // 视频2评论
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 2,
          userId: 4,
          content:
              "This fragrance has become my signature scent! Thanks for the detailed explanation",
          createdAt: DateTime.now().subtract(Duration(days: 1)),
        ),
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 2,
          userId: 5,
          content:
              "I just bought this and it smells exactly like described here! Perfect match.",
          createdAt: DateTime.now().subtract(Duration(hours: 8)),
        ),

        // 视频3评论
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 3,
          userId: 6,
          content:
              "The base notes really do last all day, this review is spot on! 👌",
          createdAt: DateTime.now().subtract(Duration(days: 3)),
        ),
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 3,
          userId: 7,
          content:
              "Woody scents are my favorite and this video convinced me to try this one!",
          createdAt: DateTime.now().subtract(Duration(hours: 20)),
        ),

        // 视频4评论
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 4,
          userId: 2,
          content:
              "Citrus perfumes always remind me of summer vacations! This one looks perfect ☀️",
          createdAt: DateTime.now().subtract(Duration(days: 4)),
        ),
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 4,
          userId: 5,
          content:
              "I wear citrus scents year-round for that extra energy boost!",
          createdAt: DateTime.now().subtract(Duration(hours: 15)),
        ),
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 4,
          userId: 3,
          content:
              "The bergamot note in this fragrance is incredible, just got mine yesterday!",
          createdAt: DateTime.now().subtract(Duration(hours: 2)),
        ),

        // 视频5评论
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 5,
          userId: 7,
          content:
              "Floral scents are underrated! This video captures their essence perfectly 🌸",
          createdAt: DateTime.now().subtract(Duration(days: 2)),
        ),
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 5,
          userId: 4,
          content:
              "I gifted this to my mom and she absolutely loves it! Great recommendation.",
          createdAt: DateTime.now().subtract(Duration(hours: 12)),
        ),

        // 视频6评论
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 6,
          userId: 3,
          content:
              "Oriental scents are so mysterious and captivating! This is now on my wishlist ✨",
          createdAt: DateTime.now().subtract(Duration(days: 5)),
        ),
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 6,
          userId: 5,
          content:
              "This is perfect for evening events, the spicy notes really stand out!",
          createdAt: DateTime.now().subtract(Duration(hours: 30)),
        ),
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 6,
          userId: 2,
          content:
              "My partner loves when I wear this fragrance, instant compliments!",
          createdAt: DateTime.now().subtract(Duration(hours: 6)),
        ),

        // 视频7评论
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 7,
          userId: 6,
          content:
              "Fougere fragrances are classic for a reason. This one is exceptional!",
          createdAt: DateTime.now().subtract(Duration(days: 1)),
        ),
        VideoCommentModel(
          id: _uuid.v4(),
          videoId: 7,
          userId: 4,
          content:
              "The lavender note is so calming, makes this a perfect evening scent 🌙",
          createdAt: DateTime.now().subtract(Duration(hours: 10)),
        ),
      ];

      await saveAllComments(sampleComments);
    }
  }

  // 获取所有评论
  static Future<List<VideoCommentModel>> getAllComments() async {
    return SpUtil.getModelList<VideoCommentModel>(
      _spKey,
      (json) => VideoCommentModel.fromJson(json),
    );
  }

  // 保存所有评论
  static Future<void> saveAllComments(List<VideoCommentModel> comments) async {
    await SpUtil.setModelList(_spKey, comments);
  }

  // 获取特定视频的评论
  static Future<List<VideoCommentModel>> getCommentsByVideoId(
    int videoId,
  ) async {
    final allComments = await getAllComments();
    return allComments.where((comment) => comment.videoId == videoId).toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt)); // 按时间降序排列
  }

  // 添加评论
  static Future<VideoCommentModel> addComment(
    int videoId,
    int userId,
    String content,
  ) async {
    final allComments = await getAllComments();

    // 创建新评论
    final newComment = VideoCommentModel(
      id: _uuid.v4(),
      videoId: videoId,
      userId: userId,
      content: content,
      createdAt: DateTime.now(),
    );

    allComments.add(newComment);
    await saveAllComments(allComments);

    // 更新视频的评论数
    final videos = VideoService.getVideoList();
    final videoIndex = videos.indexWhere((v) => v.id == videoId);
    if (videoIndex != -1) {
      final video = videos[videoIndex];
      final updatedVideo = VideoModel(
        id: video.id,
        description: video.description,
        url: video.url,
        coverUrl: video.coverUrl,
        collectCount: video.collectCount,
        likeCount: video.likeCount,
        commentCount: video.commentCount + 1,
      );
      await VideoService.updateVideo(updatedVideo);
    }

    return newComment;
  }

  // 删除评论
  static Future<bool> deleteComment(String commentId) async {
    final allComments = await getAllComments();

    try {
      final comment = allComments.firstWhere((c) => c.id == commentId);
      final int videoId = comment.videoId;
      allComments.removeWhere((c) => c.id == commentId);
      await saveAllComments(allComments);

      // 更新视频的评论数
      final videos = VideoService.getVideoList();
      final videoIndex = videos.indexWhere((v) => v.id == videoId);
      if (videoIndex != -1) {
        final video = videos[videoIndex];
        final updatedVideo = VideoModel(
          id: video.id,
          description: video.description,
          url: video.url,
          coverUrl: video.coverUrl,
          collectCount: video.collectCount,
          likeCount: video.likeCount,
          commentCount: math.max(0, video.commentCount - 1),
        );
        await VideoService.updateVideo(updatedVideo);
      }

      return true;
    } catch (e) {
      return false;
    }
  }
}
